import { createStore } from 'vuex'
import { ElMessage } from 'element-plus'
export default createStore({
  state: {
    user: {
      // 从缓存中判断是否有用户数据，若有则为登录状态，无则未登录为空
      username:
        window.localStorage.getItem('user' || '[]') == null
          ? ''
          : JSON.parse(window.localStorage.getItem('user' || '[]')).username,
    },
    // 默认购物车数据，有个bug，先删除购物车中初始化数据，再操作购物车比较好
    car: [
      {
        goodsId: '1',
        goodsName: '桂圆红枣茶',
        goodsNum: 5,
        goodsPrice: 35,
        goodsImgurl: 'https://img1.imgtp.com/2023/06/06/B4UmSaoj.jpg',
      },
    ],
  },
  getters: {},
  mutations: {
    // 登录，将数据存进缓存
    login(state, user) {
      state.user = user
      window.localStorage.setItem('user', JSON.stringify(user))
    },
    // 增加购物车
    addToCar(state, goods) {
      var flag = false
      state.car.some((item) => {
        if (item.goodsId == goods.goodsId) {
          console.log('重复了')
          ElMessage({
            message: '已存在商品',
            type: 'success',
          })
          console.log(item.goodsNum)
          item.goodsNum += parseInt(goods.goodsNum)
          console.log(item.goodsNum)
          flag = true
          return true
        }
      })
      if (!flag) {
        state.car.push(goods)
        ElMessage({
          message: '添加成功',
          type: 'success',
        })
      }
      // 将购物车信息存入缓存
      localStorage.setItem('car', JSON.stringify(state.car))
    },

    // 删除购物车
    delToCar(state, goods) {
      state.car.some((item) => {
        console.log(item)
        if (item.goodsId == goods) {
          console.log('购物车没有商品')
        } else {
          state.car.splice(item, 1)
          console.log('删除成功')
        }
      })
      localStorage.setItem('car', JSON.stringify(state.car))
    },
  },
  actions: {},
  modules: {},
})
